package com.msgc.utils.crypto.asymmetric.store.impl;

import com.msgc.utils.crypto.asymmetric.exception.NoSuchKeyPairException;
import com.msgc.utils.crypto.asymmetric.store.KeyPairCache;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import java.security.KeyPair;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * RSA 秘钥存储-本地存储，适合单机部署场景
 * @author liuyanming 2019年12月18日
 */
public class LocalKeyPairCache implements KeyPairCache {
	protected ConcurrentMap<String, KeyPair> store = new ConcurrentHashMap<>();
	
	@PostConstruct
	public void init() {
		LoggerFactory.getLogger(LocalKeyPairCache.class).debug("KeyPairCache-local init.");
	}
	
	@Override
	public void set(String id, KeyPair keyPair) {
		store.put(id, keyPair);
	}
	
	@Override
	public KeyPair get(String id) throws NoSuchKeyPairException {
		KeyPair keyPair = store.get(id);
		if(keyPair != null){
			return keyPair;
		}else {
			throw new NoSuchKeyPairException("can't found keyPair id=" + id);
		}
	}

	@Override
	public void destroy() {
		store.clear();
	}
	
}
